﻿using System;
using System.Net;

namespace SharePointUtilitiesForDevelopers.Service
{
    /// <summary>
    /// Caches the client credentials used when calling SharePoint web servies.
    /// </summary>
    public static class SharePointServiceCredentialCache
    {
        private static CredentialCache _credentialCache = new CredentialCache();
        private const string AuthenticationType = "Ntlm";
        
        /// <summary>
        /// Sets the credential using default credentials.
        /// </summary>
        /// <param name="siteUrl">The site URL.</param>
        public static void SetCredential(string siteUrl)
        {
            SetCredential(siteUrl, CredentialCache.DefaultNetworkCredentials);
        }
        
        /// <summary>
        /// Sets the credential using the user name and password.
        /// </summary>
        /// <param name="siteUrl">The site URL.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        public static void SetCredential(string siteUrl, string userName, string password)
        {
            SetCredential(siteUrl, new NetworkCredential(userName, password));
        }

        /// <summary>
        /// Sets the credential.
        /// </summary>
        /// <param name="siteUrl">The site URL.</param>
        /// <param name="credential">The credential.</param>
        public static void SetCredential(string siteUrl, NetworkCredential credential)
        {
            // Create Uri
            var uri = new Uri(siteUrl);

            // Remove existing
            _credentialCache.Remove(uri, AuthenticationType);

            // Add
            _credentialCache.Add(uri, AuthenticationType, credential);
        }

        /// <summary>
        /// Gets the credential.
        /// </summary>
        /// <param name="siteUrl">The site URL.</param>
        /// <returns></returns>
        public static NetworkCredential GetCredential(string siteUrl)
        {
            // Create Uri
            var uri = new Uri(siteUrl);

            // Get the credential for the url
            var credential = _credentialCache.GetCredential(uri, AuthenticationType);

            return credential;
        }

        /// <summary>
        /// Clears the cache.
        /// </summary>
        public static void Clear()
        {
            _credentialCache = new CredentialCache();
        }

    }
}